import 'package:flutter/material.dart';
import 'dart:async';
import '../../utils/G.dart';
import 'package:provider/provider.dart';
import '../../providers/user_provider.dart';

class ChangePassword extends StatefulWidget {
  const ChangePassword({Key? key}) : super(key: key);

  @override
  _ChangePasswordState createState() => _ChangePasswordState();
}

class _ChangePasswordState extends State<ChangePassword> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _password = ''; // 密码
  String _repassword = ""; // 确认密码
  String _captcha = ''; // 验证码
  String _captchaText = '获取验证码';
  bool _isSent = false;

  late Timer _timer;
  int _counter = 60;
  String _verifyCode = "";
  Map _userInfo = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 获取发送短信的凭证
    _getVerifyCode();
  }

  void _getVerifyCode() async {
    var res = await G.api.user.verifyCode();
    if (res['status'] == 200) {
      _verifyCode = res['data']['key'];
    }
  }

  @override
  Widget build(BuildContext context) {
    _userInfo = context.read<UserProvider>().userInfo;

    return Scaffold(
        appBar: AppBar(
          title: const Text('修改密码'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          padding: const EdgeInsets.all(20),
          physics: const BouncingScrollPhysics(),
          child: Column(
            children: [
              // 顶部 Logo
              const SizedBox(
                height: 40,
              ),
              Center(
                child: Text(_userInfo['phone'],
                    style: const TextStyle(fontSize: 28)),
              ),
              const SizedBox(
                height: 60,
              ),

              // 表单
              _renderChangePasswordForm(),

              // 页脚
            ],
          ),
        ));
  }

  Widget _renderChangePasswordForm() {
    return Form(
        key: _formKey,
        child: Column(
          children: [
            TextFormField(
                // keyboardType: TextInputType.number,
                obscureText: true,
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.password),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '设置新密码'),
                validator: (value) {
                  if (value.toString().length < 6) {
                    return '密码最短是 6 位';
                  }
                  return null;
                },
                onChanged: (value) {
                  _password = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
                // keyboardType: TextInputType.number,
                obscureText: true,
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.password),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '确认新密码'),
                validator: (value) {
                  if (value.toString().length < 6) {
                    return '密码最短是 6 位';
                  }
                  return null;
                },
                onChanged: (value) {
                  _repassword = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.password),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '验证码',
                    suffixIcon: TextButton(
                        onPressed: _captchaCallback(),
                        child: Text(_captchaText))),
                validator: (value) {
                  return value!.isEmpty ? "请输入验证码" : null;
                },
                onChanged: (value) {
                  _captcha = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            Row(
              children: [
                Expanded(
                    child: ElevatedButton(
                        onPressed: () async {
                          if (_formKey.currentState?.validate() as bool) {
                            if (_password != _repassword) {
                              G.error('两次输入的密码不一致');
                            } else {
                              // 重置倒计时
                              _resetCountDown();

                              // 调用登陆接口
                              var res = await G.api.user.changePassword(
                                  _userInfo['phone'], _password, _captcha);
                              if (res['status'] == 200) {
                                // 跳转到个人中心
                                Future.delayed(
                                    const Duration(milliseconds: 500), () {
                                  G.router.navigateTo(context, '/mine');
                                });
                              } else {
                                // G.error(res['msg']);
                                G.error('修改失败');
                              }
                            }
                          }
                        },
                        child: const Text('保存'),
                        style: ButtonStyle(
                            padding: MaterialStateProperty.all(
                                const EdgeInsets.all(12)))))
              ],
            )
          ],
        ));
  }

  _captchaCallback() {
    // 如果验证码已经发送，则倒计时效果，不能再点击
    if (_isSent) {
      // 按钮的回调函数为 null，则按钮不可点击
      return null;
    } else {
      return () async {
        // 倒计时
        countDown();

        // 发送验证码
        // @todo 调用发送验证码接口
        var res = await G.api.user.sendCaptcha(
            phone: _userInfo['phone'], key: _verifyCode, type: 'reset');
        if (res['status'] == 200) {
          _isSent = true;
          // 提示框
          G.success('发送成功');
        } else {
          // 提示框
          G.error('发送失败');
        }
      };
    }
  }

  countDown() {
    var _duration = const Duration(seconds: 1);

    Timer(_duration, () {
      _timer = Timer.periodic(_duration, (timer) {
        _counter--;
        if (_counter == 0) {
          _resetCountDown();
        } else {
          setState(() {
            _captchaText = "剩余 " + _counter.toString() + " 秒";
          });
        }
      });
    });
  }

  void _resetCountDown() {
    setState(() {
      _timer.cancel();
      _isSent = false;
      _counter = 60;
      _captchaText = "获取验证码";
    });
  }
}
